package cn.fl.finance.service.impl;

import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.finance.api.IFinLoanDtlApiService;
import cn.fl.finance.api.IFinLoanInfoApiService;
import cn.fl.finance.api.IFinPayApplyInfoApiService;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.condition.FinLoanDtlQC;
import cn.fl.finance.condition.FinPayApplyInfoQC;
import cn.fl.finance.condition.FinPayDtlQC;
import cn.fl.finance.constant.FinFlowFormUrlConstant;
import cn.fl.finance.constant.FinFlowModelConstant;
import cn.fl.finance.dto.FinLoanDtlDTO;
import cn.fl.finance.dto.FinLoanInfoDTO;
import cn.fl.finance.dto.FinPayApplyInfoDTO;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.finance.service.IFinLoanInfoService;
import cn.fl.finance.transform.FinLoanInfoVOTransform;
import cn.fl.finance.vo.FinLoanInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 借款记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class FinLoanInfoServiceImpl implements IFinLoanInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(FinLoanInfoServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IFinLoanInfoApiService finLoanInfoApiService;

	@Autowired
	private IFinPayApplyInfoApiService finPayApplyInfoApiService;
	@Autowired
	private IFinPayDtlApiService finPayDtlApiService;

	@Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构
	@Autowired
	private IFinLoanDtlApiService loanDtlApiService;

	@Override
	public FinLoanInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		FinLoanInfoDTO dto = finLoanInfoApiService.selectById(id);
		return FinLoanInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(FinLoanInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		entity.setCstMgrRgnCd(CurrentThreadContext.getCurrentRgnDivCd());
		return this.finLoanInfoApiService.add(FinLoanInfoVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.finLoanInfoApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public void modify(FinLoanInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
		}
		this.finLoanInfoApiService.updateFinLoanInfoDTO(FinLoanInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
    	try{
			if(null == page)page = new Pager();
			page = this.finLoanInfoApiService.searchListPage(page);
			if (CollectionUtils.isNotEmpty(page.getResultList())) {
				List<Long> loanIds = new ArrayList();//借款记录id list
				List<FinLoanInfoVO> voList = FinLoanInfoVOTransform.toVOList((List<FinLoanInfoDTO>) page.getResultList());
				for(FinLoanInfoVO f : voList){
					loanIds.add(f.getId());
				}

				//a
				//付款申请list start
				List<Long> payApplyIds = new ArrayList<>();//付款申请信息 id集合
				Map<Long,FinPayApplyInfoDTO> payApplyInfoMap = new HashMap<>();//付款申请信息 map
				FinPayApplyInfoQC payApplyInfoQC = new FinPayApplyInfoQC();
				payApplyInfoQC.setLoanIds(loanIds);
				List<FinPayApplyInfoDTO> finPayApplyInfoDTOS = this.finPayApplyInfoApiService.searchList(payApplyInfoQC);
				if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)){
					for(FinPayApplyInfoDTO pa : finPayApplyInfoDTOS){
						payApplyIds.add(pa.getId());
						payApplyInfoMap.put(pa.getId(),pa);
					}
				}
				//付款申请list end

				//付款明细list start
				FinPayDtlQC payDtlQC = new FinPayDtlQC();
				payDtlQC.setPayApplyIds(payApplyIds);
				//按实际付款时间倒叙
				//payDtlQC.setSortName("ACT_PAY_TM");
				//payDtlQC.setSortOrder("DESC");
				List<FinPayDtlDTO> finPayDtlDTOS = finPayDtlApiService.selectList(payDtlQC);

				Map<Long,Long> payApplyIdActPayAmtMap = new HashMap();//付款申请id与总实际付款金额Map
				if(CollectionUtils.isNotEmpty(finPayDtlDTOS)){

					for(FinPayDtlDTO d : finPayDtlDTOS){
						if(CollectionUtils.isMapNotEmpty(payApplyInfoMap) && payApplyInfoMap.containsKey(d.getPayApplyId())){
							if(StringUtils.isNotEmpty(d.getActPayAmt())){
								Long actPayAmtSum = d.getActPayAmt();
								if(CollectionUtils.isMapNotEmpty(payApplyIdActPayAmtMap) && payApplyIdActPayAmtMap.containsKey(d.getPayApplyId())){
									payApplyIdActPayAmtMap.put(d.getPayApplyId(),actPayAmtSum + payApplyIdActPayAmtMap.get(d.getPayApplyId()));
								}else{
									payApplyIdActPayAmtMap.put(d.getPayApplyId(),actPayAmtSum);
								}
							}
						}
					}

				}
				//付款明细list end

				//拼接数据 start
				Map<Long,Long> loanIdActPayAmtMap = new HashMap();//借款记录id与总实际付款金额Map
				if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)){
					for(FinPayApplyInfoDTO pa : finPayApplyInfoDTOS){
						if(CollectionUtils.isMapNotEmpty(payApplyIdActPayAmtMap) && payApplyIdActPayAmtMap.containsKey(pa.getId())){
							pa.setActPayAmtSum(payApplyIdActPayAmtMap.get(pa.getId()));
							if(StringUtils.isNotEmpty(pa.getActPayAmtSum())){
								long actPayAmtSum = pa.getActPayAmtSum();
								if(CollectionUtils.isMapNotEmpty(loanIdActPayAmtMap) && loanIdActPayAmtMap.containsKey(pa.getLoanId())){
									loanIdActPayAmtMap.put(pa.getLoanId(),actPayAmtSum + loanIdActPayAmtMap.get(pa.getLoanId()));
								}else{
									loanIdActPayAmtMap.put(pa.getLoanId(),actPayAmtSum);
								}
							}
						}
					}
				}

				for(FinLoanInfoVO f : voList){
					if(CollectionUtils.isMapNotEmpty(loanIdActPayAmtMap) && loanIdActPayAmtMap.containsKey(f.getId())){
						f.setActPayAmtSum(loanIdActPayAmtMap.get(f.getId()));
						if(StringUtils.isNotEmpty(f.getLoanAmt())){
							f.setPendPayAmt(f.getLoanAmt() - f.getActPayAmtSum());
						}
					}else{
						if(StringUtils.isNotEmpty(f.getLoanAmt())) {
							f.setPendPayAmt(f.getLoanAmt());
						}
					}
				}
				//拼接数据 end
				//a

				page.setResultList(voList);
			}
			return page;
		}catch(Exception e){
			BaseLogUtils.info(logger, "searchListPage", "查询借款记录数据失败:" + JSONObject.toJSONString(e.getMessage()));
			throw e;
		}
	}

	/**
	 * 借款还款管理列表
	 * @param page
	 * @return
	 * @throws BaseException
	 */
	@Override
	public Pager selectLoanPayPage(Pager page) throws BaseException{
		page = finLoanInfoApiService.selectLoanPayPage(page);
		List<FinLoanInfoDTO> vos = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(page.getResultList())){
			vos = (List<FinLoanInfoDTO>)page.getResultList();
		}
		//所属公司 start
		List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
		Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SysOrgDTO sysOrgDTO : list) {
				buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
			}
		}
		SysOrgDTO sysOrgDTO = null;
		String orgCd = null;

		if(CollectionUtils.isNotEmpty(vos)){
			for(FinLoanInfoDTO vo :vos){
				if (buOrgCdMap.containsKey(vo.getCstMgrOrgCd())) {
					sysOrgDTO = buOrgCdMap.get(vo.getCstMgrOrgCd());
					vo.setCstMgrOrgCdNm(sysOrgDTO.getOrgNm());
					orgCd = sysOrgDTO.getOrgCd();
					while(orgCd.length()>8){
						if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
							vo.setCyOrgCdNm(sysOrgDTO.getOrgNm());
						}else if("3".equals(sysOrgDTO.getOrgTypCd())){
							vo.setPrOrgCdNm(sysOrgDTO.getOrgNm());
							break;
						}
						orgCd = orgCd.substring(0,orgCd.length()-4);
						if(buOrgCdMap.containsKey(orgCd)){
							sysOrgDTO = buOrgCdMap.get(orgCd);
						}else{
							break;
						}
					}
					if(StringUtils.isNotBlank(vo.getPDefKey())){
						if(vo.getPDefKey().equals(FinFlowModelConstant.FLOW_ASS_TRAILER_PRE_ID)){
							vo.setFormUrl(FinFlowFormUrlConstant.ASS_TRAILER_FORM_URL);
						}else {
							vo.setFormUrl(FinFlowFormUrlConstant.LOAN_FORM_URL);
						}
					}

				}
			}
		}
		//所属公司 end
		return page;
	}

	@Override
	public Long getTotalAmt(Long loanInfoId) {
		Long res = 0l;
		FinLoanDtlQC qc = new FinLoanDtlQC();
		qc.setLoanId(loanInfoId);
		List<FinLoanDtlDTO> finLoanDtlDTOS = this.loanDtlApiService.selectList(qc);
		if(CollectionUtils.isNotEmpty(finLoanDtlDTOS)){
			for (FinLoanDtlDTO finLoanDtlDTO : finLoanDtlDTOS) {
				res += finLoanDtlDTO.getLoanAmt();
			}
		}
		return res;
	}
}
